package com.shuyou;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.shuyou.net.BookDetail;
import com.shuyou.net.JsonParser;
import com.shuyou.net.ServerInfo;
import com.shuyou.net.StaticHttpClient;
import com.shuyou.net.UserInfo;
import com.shuyou.values.Values;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class BarCodeScanResultActivity extends Activity {

	private static final String TAG = "UploadBookActivity";

	private EditText mEditText;
	private TextView mTextNum;
	private TextView mTextMaxNum;
	
	private Dialog dialogUsrInfo;
	
	private String barcode;
	private String barcodeFormat;

	private Map<String, String> map;
	
	private ServerInfo si = null;
	private Thread uploadThread = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_uploadbook);
		
		mEditText = (EditText)findViewById(R.id.uploadbook_edittext);
		mEditText.addTextChangedListener(mTextWatcher);
		mTextNum = (TextView)findViewById(R.id.uploadbook_textnum);
		mTextNum.setText(String.valueOf(Values.MAX_TEXT_COUNT));
		mTextMaxNum = (TextView)findViewById(R.id.uploadbook_textmaxnum);
		mTextMaxNum.setText("/" + Values.MAX_TEXT_COUNT);
		
		LinearLayout dialogUsrInfoView = (LinearLayout)getLayoutInflater()
				.inflate(R.layout.shuyou_dialog_scanresult_confirm, null);
		dialogUsrInfo = new Dialog(BarCodeScanResultActivity.this, R.style.ShuyouDialog);
		dialogUsrInfo.setContentView(dialogUsrInfoView);
		
		InitTopButton();
		
		findViewById(R.id.mybooks_top).setVisibility(View.INVISIBLE);
		mEditText.setVisibility(View.INVISIBLE);
		mTextNum.setVisibility(View.INVISIBLE);
		mTextMaxNum.setVisibility(View.INVISIBLE);
		
		barcode = getIntent().getStringExtra("barcode");
		barcodeFormat = getIntent().getStringExtra("barcodeFormat");
		if((barcodeFormat.equals("EAN_13") && barcode.startsWith("978"))){
			/*如果是扫描书的一维码，显示编辑备注内容*/
			findViewById(R.id.mybooks_top).setVisibility(View.VISIBLE);
			mEditText.setVisibility(View.VISIBLE);
			mTextNum.setVisibility(View.VISIBLE);
			mTextMaxNum.setVisibility(View.VISIBLE);
			
		} else if (barcodeFormat.equals("QR_CODE")
				&& barcode.startsWith("#shuyou#")) {
			// 判断是借书还是还书
			dialogUsrInfo.show();
			dialogUsrInfo.setCancelable(false); //弹窗不能被关闭
			dialogUsrInfo.findViewById(R.id.dialog_scanresult_button).setVisibility(View.GONE);
			
			String temp = barcode.substring(8);
			String type = temp.substring(0, 1);// type:1代表用户上传的书，是借书二维码。3代表借入的书，是还书二维码
			
			if (type.endsWith("l")) {// 调用借书接口
				String days = temp.substring(1, 3);
				String str_secret = temp.substring(3);
				lendBook(str_secret, days, UserInfo.sessionid,
						UserInfo.platform_userid);
			} else if (type.endsWith("r")) { // 调用还书接口
				String str_secret = temp.substring(1);
				returnBook(str_secret, UserInfo.sessionid,
						UserInfo.platform_userid);
			} else {
				Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getApplicationContext(), "该码格式不正确", Toast.LENGTH_SHORT).show();
			finish();
		}

	}
	
	/**
	 * 对头部返回和确定的监控
	 */
	private void InitTopButton() {
		findViewById(R.id.uploadbook_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		findViewById(R.id.uploadbook_confirm).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String comment = mEditText.getText().toString();
				uploadBook(barcode, comment, UserInfo.sessionid,
						UserInfo.platform_userid);
				
				dialogUsrInfo.show();
				dialogUsrInfo.setCancelable(false); //弹窗不能被关闭
				dialogUsrInfo.findViewById(R.id.dialog_scanresult_button).setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						finish();
					}
				});
			}
			
		});
	}

	private void uploadBook(String isbn, String comment, String sessionid,
			String platform_userid) {
		map = new HashMap<String, String>();
		map.put("isbn", isbn);
		map.put("comment", comment);
		map.put("sessionid", sessionid);
		map.put("platform_userid", platform_userid);
		uploadThread = new Thread() {

			@Override
			public void run() {
				try {
					String strResult = StaticHttpClient.doPost(Values.UPLOAD_BOOK_URL,
							map);
					si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);
					String status = si.getStatus();
					if (status.equals("10000")) {
						Message message = new Message();
						message.what = Values.SUCCESS_TO_UPLOAD;
						message.obj = si.getData().getBookDetail();
						handler.sendMessage(message);
					} else if (status.equals("10003")) {
						Message message = new Message();
						message.what = Values.FAIL_TO_UPLOAD;
						message.obj = "系统内部错误";
						handler.sendMessage(message);
					} else if (status.equals("30001")) {
						Message message = new Message();
						message.what = Values.FAIL_TO_UPLOAD;
						message.obj = "没有找到该书";
						handler.sendMessage(message);
					} else if (status.equals("30002")) {
						Message message = new Message();
						message.what = Values.FAIL_TO_UPLOAD;
						message.obj = "您已上传过该书";
						handler.sendMessage(message);
					} else {
						Message message = new Message();
						message.what = Values.FAIL_TO_UPLOAD;
						message.obj = "未知错误";
						handler.sendMessage(message);
					}
					Log.i(TAG, strResult);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}

		};
		uploadThread.start();
	}
	
	private TextWatcher mTextWatcher = new TextWatcher() {  
		  
        private int editStart;  
  
        private int editEnd;  
  
        public void afterTextChanged(Editable s) {  
            editStart = mEditText.getSelectionStart();  
            editEnd = mEditText.getSelectionEnd();  
  
            // 先去掉监听器，否则会出现栈溢出  
            mEditText.removeTextChangedListener(mTextWatcher);  
  
            // 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度  
            // 因为是中英文混合，单个字符而言，calculateLength函数都会返回1  
            while (calculateLength(s.toString()) > Values.MAX_TEXT_COUNT) { // 当输入字符个数超过限制的大小时，进行截断操作  
                s.delete(editStart - 1, editEnd);  
                editStart--;  
                editEnd--;  
            }  
            // mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了，多谢@ainiyidiandian的提醒  
            mEditText.setSelection(editStart);  
  
            // 恢复监听器  
            mEditText.addTextChangedListener(mTextWatcher);  
  
            setLeftCount();  
        }  
  
        /** 
         * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1 
         *  
         * @param c 
         * @return 
         */  
        private long calculateLength(CharSequence c) {  
            double len = 0;  
            for (int i = 0; i < c.length(); i++) {  
                int tmp = (int) c.charAt(i);  
                if (tmp > 0 && tmp < 127) {  
                    len += 0.5;  
                } else {  
                    len++;  
                }  
            }  
            return Math.round(len);  
        }  
      
        /** 
         * 刷新剩余输入字数,最大值新浪微博是140个字，人人网是200个字 
         */  
        private void setLeftCount() {  
        	mTextNum.setText(String.valueOf((Values.MAX_TEXT_COUNT - getInputCount())));  
        }  
      
        /** 
         * 获取用户输入的分享内容字数 
         *  
         * @return 
         */  
        private long getInputCount() {  
            return calculateLength(mEditText.getText().toString());  
        }  
        
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
  
        }  
  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {  
  
        }  
    };
    
    private void returnBook(String str_secret, String sessionid,
			String platform_userid) {
		final Map<String, String> map = new HashMap<String, String>();
		map.put("str_secret", str_secret);
		map.put("sessionid", sessionid);
		map.put("platform_userid", platform_userid);
		new Thread(){
			@Override
			public void run() {
				try {
					String strResult = StaticHttpClient.doPost(Values.RETURN_BOOK_URL,
							map);
					Log.i(TAG, strResult);
					ServerInfo si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);
					if(si == null) {
						Log.i(TAG, "si = null");
					} else {
						System.out.println(si);
						String status = si.getStatus();
						if (status.equals("10000")) {
							Message message = new Message();
							message.what = Values.SUCCESS_TO_RETURN;
							message.obj = si.getData();
							handler.sendMessage(message);
						} else if(status.equals("10003")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_RETURN;
							message.obj = "系统内部错误";
							handler.sendMessage(message);
						} else if(status.equals("30003")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_RETURN;
							message.obj = "二维码信息错误";
							handler.sendMessage(message);
						} else if(status.equals("30006")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_RETURN;
							message.obj = "不是该用户借的书";
							handler.sendMessage(message);
						} else if(status.equals("30007")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_RETURN;
							message.obj = "没有该书的借出记录";
							handler.sendMessage(message);
						} else {
							Message message = new Message();
							message.what = Values.FAIL_TO_RETURN;
							message.obj = "未知错误";
							handler.sendMessage(message);
						}
					}
					
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}
				
			}
			
		}.start();
	}

	private void lendBook(String str_secret, String limit_time,
			String sessionid, String platform_userid) {
		final Map<String, String> map = new HashMap<String, String>();
		map.put("str_secret", str_secret);
		map.put("limit_time", limit_time);
		map.put("sessionid", sessionid);
		map.put("platform_userid", platform_userid);
		new Thread() {

			@Override
			public void run() {
				try {
					String strResult = StaticHttpClient.doPost(Values.BORROW_BOOK_URL,
							map);
					if(strResult.equals(null)) {
						Log.i(TAG, "strResult = null");
					} else {
						Log.i(TAG, strResult);
					}
					
					ServerInfo si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);
					if(si == null) {
						Log.i(TAG, "si = null");
					} else {
						System.out.println(si);
						String status = si.getStatus();
						if (status.equals("10000")) {
							Message message = new Message();
							message.what = Values.SUCCESS_TO_BORROW;
							message.obj = si.getData();
							handler.sendMessage(message);
						} else if(status.equals("10003")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							handler.sendMessage(message);
						} else if(status.equals("30003")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "服务器内部错误";
							
							handler.sendMessage(message);
						} else if(status.equals("30004")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "不能借自己的书";
							
							handler.sendMessage(message);
						} else if(status.equals("30005")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "该书已借出";
							handler.sendMessage(message);
						} else if(status.equals("30011")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "您借入的书超出借出的两本";
							handler.sendMessage(message);
						} else if(status.equals("30012")) {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "借入的书超过八本";
							handler.sendMessage(message);
						} else {
							Message message = new Message();
							message.what = Values.FAIL_TO_BORROW;
							message.obj = "未知错误";
							handler.sendMessage(message);
						}	
					}
				}catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message message = new Message();
					message.what = Values.NETWORK_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}

		}.start();
	}
	
    /**
	 * 静态handler,防止内存泄漏错误
	 * @author chris
	 *
	 */
	static class MyInnerHandler extends Handler {
        WeakReference<BarCodeScanResultActivity> mActivity;

        MyInnerHandler(BarCodeScanResultActivity mAct) {
        	mActivity = new WeakReference<BarCodeScanResultActivity>(mAct);
        }

        @Override
        public void handleMessage(Message msg) {
        	BarCodeScanResultActivity theAct = mActivity.get();
        	switch (msg.what) {
        	case Values.FAIL_TO_UPLOAD:
				Toast.makeText(theAct, (String)msg.obj, Toast.LENGTH_SHORT).show();
				theAct.finish();
				break;
			case Values.SUCCESS_TO_UPLOAD:
				BookDetail ib = (BookDetail)msg.obj;
				theAct.dialogUsrInfo.findViewById(R.id.dialog_scanresult_process).setVisibility(View.GONE);
				theAct.dialogUsrInfo.findViewById(R.id.dialog_scanresult_content).setVisibility(View.VISIBLE);
				TextView textBookName = (TextView)theAct.dialogUsrInfo.findViewById(R.id.dialog_scanresult_bookname);
				textBookName.setText(ib.getBook_name());
				TextView textAuthorName = (TextView)theAct.dialogUsrInfo.findViewById(R.id.dialog_scanresult_bookauthor);
				textAuthorName.setText(ib.getAuthor());
                
				break;
			case Values.SUCCESS_TO_BORROW:
        		Toast.makeText(theAct, "借书成功", Toast.LENGTH_SHORT).show();
        		theAct.finish();
        		break;
        	case Values.FAIL_TO_BORROW:
        		Toast.makeText(theAct, "借书失败," + msg.obj.toString(), Toast.LENGTH_SHORT).show();
        		theAct.finish();
        		break;
        	case Values.SUCCESS_TO_RETURN:
        		Toast.makeText(theAct, "还书成功", Toast.LENGTH_SHORT).show();
        		theAct.finish();
        		break;
        	case Values.FAIL_TO_RETURN:
        		Toast.makeText(theAct, "还书失败," + msg.obj.toString(), Toast.LENGTH_SHORT).show();
        		theAct.finish();
        		break;
			case Values.NETWORK_ERROR:
				theAct.dialogUsrInfo.cancel();
				Toast.makeText(theAct, "网络连接超时", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
	    }
	 }
	 MyInnerHandler handler = new MyInnerHandler(this);
    
}
